package com.jintoufs.weixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jintoufs.domain.auth.AuthImg;
import com.jintoufs.domain.constants.Constants;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.service.account.WithdrawService;
import com.jintoufs.service.authImg.AuthImgService;
import com.jintoufs.service.customer.CustomerService;
import com.jintoufs.service.image.ImageService;
import com.jintoufs.service.user.PasswordHelper;
import com.jintoufs.util.CardCodeGenerator;
import com.jintoufs.util.http.HttpUtils;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.util.weixin.AesCbcUtil;
import com.jintoufs.util.weixin.WeixinMessagePush;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by yh on 2015/6/16.
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/customer")
public class CustomerAction extends SupportAction {
    private Log logger = LogFactory.getLog(CustomerAction.class);
    @Resource
    private CustomerService customerService;
    @Autowired
    private PasswordHelper passwordHelper;
    @Autowired
    private WeixinMessagePush weixinMessagePush;
    @Resource
    private ImageService imageService;
    @Resource
    private AuthImgService authImgService;
    @Resource
    private WithdrawService withdrawService;


    @Value("${appId}")
    private String APPID;

    @Value("${secret}")
    private String SECRET = "";

    @GetMapping("/login")
    @ResponseBody
    public AjaxMsg login(HttpServletRequest request, String code, String encryptedData, String iv, String _encryptedData, String _iv,
                         String shareId, String spreadId,String shareType) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map userInfo = new HashMap();
        //根据code获取sessionKey
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        String json = HttpUtils.getURLContent(url);
        if (!json.isEmpty()) {
            JSONObject jsonObject = JSON.parseObject(json);
            String sessionKey = jsonObject.getString("session_key");
            //尝试解密数据
            try {
                System.out.println("encryptedData:" + encryptedData);
                System.out.println("iv:" + iv);
                //用户信息
                String result = AesCbcUtil.decrypt(encryptedData, sessionKey, iv, "UTF-8");
                //用户电话
                String _result = AesCbcUtil.decrypt(_encryptedData, new String(sessionKey), _iv, "UTF-8");
                //如果解密结果不为空
                if (null != result && result.length() > 0 && !ValidUtil.isEmpty(_result)) {
//                if (null != result && result.length() > 0) {

                    //转化为JSON
                    JSONObject userInfoJSON = JSON.parseObject(result);
                    JSONObject telephoneJSON = JSON.parseObject(_result);
                    String phoneNumber = telephoneJSON.get("phoneNumber").toString();
                    String openId = userInfoJSON.getString("openId");
                    String unionId = userInfoJSON.getString("unionId");
                    String country = userInfoJSON.getString("country");
                    String gender = userInfoJSON.getString("gender");
                    String city = userInfoJSON.getString("city");
                    String avatarUrl = userInfoJSON.getString("avatarUrl");
                    String nickName = userInfoJSON.getString("nickName");
                    String language = userInfoJSON.getString("language");
                    String province = userInfoJSON.getString("province");
                    System.out.print("result:" + result);
//                    System.out.println("phoneResult" + _result);

                    //查询系统中是否有该用户
                    Map<String, Object> map = new HashMap<>();
                    map.put("openId", openId);
                    List<Customer> customers = customerService.queryByParams(map);
                    Customer customer;
                    if (customers != null && !customers.isEmpty()) {
                        //系统中有该用户
                        customer = customers.get(0);
                        userInfo.put("customerId", customer.getId());
                        userInfo.put("openId", openId);
                        String token = getUUID();
                        userInfo.put("token", token);
                        userInfo.put("sessionKey", sessionKey);
                        userInfo.put("type", customer.getType());
                        userInfo.put("shareId", customer.getRecommendId());
                        userInfo.put("auth", customer.getAuth());
                        customer.setToken(token);
//                        customer.setSpreadId(spreadId);
                        customer.setUserPhoto(avatarUrl);
                        customer.setRealName(filterEmoji(nickName));
                        customer.setUnionId(phoneNumber);
                        customer.setMobilePhone(phoneNumber);
                        customer.setAddress(country + province + city);
                        customer.setOpenId(openId);
                        customer.setUnionId(unionId);
                        customerService.update(customer);
                        ajaxMsg.setDatas(userInfo);
                    } else {
                        //系统中无该用户,则新建用户
                        customer = new Customer();
                        String newCustomerId = getUUID();
                        customer.setId(newCustomerId);
                        customer.setOpenId(openId);
                        customer.setUnionId(unionId);
                        customer.setCreateTime(new Date());
                        customer.setStatus(Constants.CUSTOMER_STATUS_NORMAL);

                        customer.setUserPhoto(avatarUrl);
                        customer.setUserName(phoneNumber);
                        customer.setRealName(filterEmoji(nickName));
                        customer.setAddress(country + province + city);
                        customer.setMobilePhone(phoneNumber);
                        String token = getUUID();
                        customer.setToken(token);
                        //供应商
                        Integer type = 0;
                        //
                        switch (shareType) {
                            //供应商邀请分销商
                            case "0":
                                type = 1;
                                customer.setPassword(CardCodeGenerator.generateRandomPassword());
                                break;
                            case "1":
                                //分销商邀请推广人
                                type = 2;
                                break;
                            default:
                                //其余的为普通分销，注册为普通用户
                                type = 3;
                                break;
                        }
                        customer.setType(type);
                        customer.setRecommendId(shareId);
                        customerService.addCustomer(customer);
                        userInfo.put("customerId", customer.getId());
                        userInfo.put("token", token);
                        userInfo.put("openId", openId);
                        userInfo.put("sessionKey", sessionKey);
                        userInfo.put("type", type);
                        userInfo.put("auth", Constants.CUSTOMER_AUTH_STATUS_NOAUTH);
                        //shareId 就是recommendId
                        userInfo.put("shareId", customer.getRecommendId());
                        ajaxMsg.setDatas(userInfo);
                    }
                } else {
                    //解密结果为空
                    ajaxMsg.setCode(AjaxMsg.FAILURE);
                    ajaxMsg.setMessage("微信登陆失败");
                    return ajaxMsg;
                }
            } catch (Exception e) {
                e.printStackTrace();
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("微信登陆失败");
                return ajaxMsg;
            }
        } else {
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("微信登录失败");
            return ajaxMsg;
        }
        return ajaxMsg;
    }

    @GetMapping("/getPhone")
    @ResponseBody
    public AjaxMsg getPhone(HttpServletRequest request, String code, String _encryptedData, String _iv) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map userInfo = new HashMap();
        //根据code获取sessionKey
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        String json = HttpUtils.getURLContent(url);
        if (!json.isEmpty()) {
            JSONObject jsonObject = JSON.parseObject(json);
            String sessionKey = jsonObject.getString("session_key");
            //尝试解密数据
            try {
                //用户电话
                String _result = AesCbcUtil.decrypt(_encryptedData, sessionKey, _iv, "UTF-8");
                //如果解密结果不为空
                if (!ValidUtil.isEmpty(_result)) {

                    //转化为JSON
                    JSONObject telephoneJSON = JSON.parseObject(_result);
                    String phoneNumber = telephoneJSON.get("phoneNumber").toString();
                    System.out.println("phoneResult" + _result);
                    ajaxMsg.setDatas(phoneNumber);
                } else {
                    //解密结果为空
                    ajaxMsg.setCode(AjaxMsg.FAILURE);
                    ajaxMsg.setMessage("微信登陆失败");
                    return ajaxMsg;
                }
            } catch (Exception e) {
                e.printStackTrace();
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("微信登陆失败");
                return ajaxMsg;
            }
        } else {
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("微信登录失败");
            return ajaxMsg;
        }
        return ajaxMsg;
    }

    @GetMapping("/detail")
    @ResponseBody
    public AjaxMsg getCustomer(String id) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Customer customer = customerService.getById(id);
        if(customer!=null){
            ajaxMsg.setCode(AjaxMsg.SUCCESS);
            ajaxMsg.setDatas(customer);
        }else{
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        }
        return ajaxMsg;
    }

    @GetMapping("/set")
    @ResponseBody
    public AjaxMsg set(String token, Float shareNumber) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Customer customer = customerService.getByToken(token);
            customer.setDividedNumber(shareNumber);
            customerService.update(customer);
        }catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            return ajaxMsg;
        }
        ajaxMsg.setCode(AjaxMsg.SUCCESS);
        return ajaxMsg;
    }
    @GetMapping("/auth/getAuth")
    @ResponseBody
    public AjaxMsg doAuth(String token){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Customer customer = customerService.getByToken(token);
            Map param = new HashMap();
            param.put("customerId", customer.getId());
            List <AuthImg> authImgs =authImgService.queryByParam(param);
            ajaxMsg.setDatas(authImgs);
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        }
        return ajaxMsg;
    }
    @PostMapping("/auth/doAuth")
    @ResponseBody
    @Transactional
    public AjaxMsg doAuth( HttpServletRequest req, HttpServletResponse res  ,String authType,String name,String token,String code){
        AjaxMsg ajaxMsg = new AjaxMsg();
        Customer customer = getCustomerByToken(token);
        if (customer!=null) {
            try {
                DefaultMultipartHttpServletRequest multipReq = (DefaultMultipartHttpServletRequest) req;
                MultiValueMap multFileMap = multipReq.getMultiFileMap();
                LinkedList fileList = (LinkedList) multFileMap.get("file");
                CommonsMultipartFile[] commonsMultipartFiles = (CommonsMultipartFile[]) fileList.toArray(new CommonsMultipartFile[fileList.size()]);
//        System.out.println(commonsMultipartFile);
                String attachment = imageService.upToCos(commonsMultipartFiles);
                String[] pathList = attachment.split(",");
                String imgPath = pathList[0];
                Map<String, Object> param = new HashMap<>();
                param.put("customerId", customer.getId());
                param.put("code", code);
                List<AuthImg> authImgs = authImgService.queryByParam(param);
                AuthImg authImg;
                if (!imgPath.contains("error")) {
                    if (authImgs.size() == 0) {
                        authImg = new AuthImg();
                        authImg.setName(name);
                        authImg.setPath(imgPath);
                        authImg.setCode(code);
                        authImg.setCustomerId(customer.getId());
                        authImgService.save(authImg, getUUID());
                    } else {
                        authImg = authImgs.get(0);
                        authImg.setPath(imgPath);
                        authImgService.save(authImg, null);
                    }
                    //更新审核状态为审核中
                    customer.setAuth(Constants.CUSTOMER_AUTH_STATUS_AUTHING);
                    customer.setAuthType(authType);
                    customerService.update(customer);
                }
            }catch (Exception e){
                e.printStackTrace();
                ajaxMsg.setCode("500");
                ajaxMsg.setMessage("服务器错误");
            }
        }else {
            ajaxMsg.setCode("500");
            ajaxMsg.setMessage("用户验证失败");
        }
        return ajaxMsg;
    }

    /**
     * @param type 2:推广人，3：消费者
     * */
    @GetMapping("/spreader/list")
    @ResponseBody
    public AjaxMsg getSpreader(String token,String type){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try{
            Map params = new HashMap();
            Customer customer = customerService.getByToken(token);
            if(customer!=null){
                params.put("recommendId",customer.getId());
                params.put("type",type);
                //购买订单相关
                List customers = customerService.queryOrderByParams(params);
                ajaxMsg.setDatas(customers);
                ajaxMsg.setCode(AjaxMsg.SUCCESS);
            }else {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("身份认证失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        }
        return ajaxMsg;
    }

    @GetMapping("/spreader/audit")
    @ResponseBody
    public AjaxMsg doAudit(String token,String id,String auth){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try{
            Customer customer = customerService.getByToken(token);
            if (ValidUtil.isEmpty(customer)) {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("身份认证失败");
                return ajaxMsg;
            }
            Customer c1 = customerService.getById(id);
            if(!ValidUtil.isEmpty(c1)){
                if("1".equals(auth)){
                    c1.setAuth("1");
                }else  if("2".equals(auth)){
                    c1.setAuth("2");
                }
                customerService.update(c1);
            }else{
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                return ajaxMsg;
            }
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        }
        return ajaxMsg;
    }
    /**
     * @param
     * */
    @GetMapping("/spreader/hasNew")
    @ResponseBody
    public AjaxMsg hasNew(String token){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try{
            Map params = new HashMap();
            Customer customer = customerService.getByToken(token);
            if(customer!=null){
                params.put("recommendId",customer.getId());
                params.put("auth","0");
                params.put("type","2");
                //购买订单相关
                List customers = customerService.queryByParams(params);
                if (!ValidUtil.isEmpty(customers)){
                    ajaxMsg.setDatas("hasNew");
                    ajaxMsg.setCode(AjaxMsg.SUCCESS);
                }
            }else {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("身份认证失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        }
        return ajaxMsg;
    }

}
